using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace Extended.NetRouting
{
    /// <summary>
    /// A series of routes
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Path as name is enough descriptive")]
    public class Path : IList<IRoute>
    {
        // Holds the routes that constitues the path
        // This list is synchronized with the list of nodes
        private readonly List<IRoute> list = new List<IRoute>();

        // The path is also a list of nodes (nodes of the path's route). This list holds the nodes.
        // This list is synchronized with the list of routes
        private readonly List<object> listOfNodes = new List<object>();

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Path"/> class.
        /// </summary>
        public Path()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Path"/> class.
        /// </summary>
        /// <param name="initialPath">The contents of this path will be copied to the new instance and will be used as initial path.</param>
        public Path(Path initialPath)
        {
            if (initialPath == null) return;
            this.list.AddRange(initialPath);
            this.listOfNodes.AddRange(initialPath.listOfNodes);
            this.Length = initialPath.Length;
            this.LastItem = initialPath.LastItem;
        }

        #endregion

        /// <summary>
        /// Gets the nodes that constitute the path.
        /// </summary>
        public object[] GetNodes()
        {
            return this.listOfNodes.ToArray();
        }

        /// <summary>
        /// Gets the total length of the path.
        /// </summary>
        public int Length { get; private set; }

        /// <summary>
        /// Gets the last item in the list
        /// </summary>
        public IRoute LastItem { get; private set; }

        #region ToString

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            return "Path " + this.ToString(".");
        }

        /// <summary>
        /// Returns a delimited <see cref="T:System.String"/> of the routes of the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="separator">The separator of the delimited string.</param>
        public string ToString(string separator)
        {
            var nodeNames = this.Select(p => p.ToString()).ToArray();
            return string.Join(separator, nodeNames);
        }

        /// <summary>
        /// Returns a delimited <see cref="T:System.String"/> of the nodes of the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="separator">The separator of the delimited string.</param>
        public string ToNodeString(string separator)
        {
            return this.ToNodeString(separator, true, true);
        }

        /// <summary>
        /// Returns a delimited <see cref="T:System.String"/> of the nodes of the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="separator">The separator of the delimited string.</param>
        /// <param name="includeStartNode">If set to <c>false</c> the first node of the path will not be included in the string.</param>
        /// <param name="includeTargetNode">If set to <c>false</c> the last node of the path will not be included in the string.</param>
        public string ToNodeString(string separator, bool includeStartNode, bool includeTargetNode)
        {
            var nodeNames = this.listOfNodes.Select(p => p.ToString()).ToArray();
            var startIndex = includeStartNode ? 0 : 1;
            var count = includeTargetNode ? nodeNames.Length - startIndex : nodeNames.Length - startIndex - 1;
            return string.Join(separator, nodeNames, startIndex, count);
        }

        #endregion

        #region IList implementation

        /// <summary>
        /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </exception>
        public void Add(IRoute item)
        {
            if (item == null) throw new ArgumentNullException("item");
            if (this.LastItem != null && this.LastItem.Target != item.Start) throw new InvalidOperationException("Start node of item should be the same as target node of last item in path");
            this.list.Add(item);
            this.Length += item.Length;
            this.LastItem = item;
            if (this.listOfNodes.Count == 0) this.listOfNodes.Add(item.Start);
            this.listOfNodes.Add(item.Target);
        }

        /// <summary>
        /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </exception>
        public void Clear()
        {
            this.Length = 0;
            this.list.Clear();
            this.listOfNodes.Clear();
            this.LastItem = null;
        }

        /// <summary>
        /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <returns>
        /// True if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </exception>
        public bool Remove(IRoute item)
        {
            if (item == null) throw new ArgumentNullException("item");
            if (item != this.LastItem) throw new InvalidOperationException("Only the last route of the path can be removed");
            this.listOfNodes.Remove(this.LastItem.Target);
            if (this.listOfNodes.Count == 1) this.listOfNodes.Remove(item.Start);
            return this.list.Remove(this.LastItem);
        }

        /// <summary>
        /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
        /// </summary>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <returns>
        /// True if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
        /// </returns>
        public bool Contains(object item)
        {
            return this.listOfNodes.Contains(item);
        }

        #endregion

        #region Rest of IList implementation (nothing fancy in here)

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<IRoute> GetEnumerator()
        {
            return this.list.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// <summary>
        /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
        /// </summary>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <returns>
        /// True if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
        /// </returns>
        public bool Contains(IRoute item)
        {
            return this.list.Contains(item);
        }

        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception>
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="array"/> is multidimensional.
        /// -or-
        /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.
        /// -or-
        /// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.
        /// -or-
        /// Type T cannot be cast automatically to the type of the destination <paramref name="array"/>.
        /// </exception>
        public void CopyTo(IRoute[] array, int arrayIndex)
        {
            this.list.CopyTo(array, arrayIndex);
        }

        /// <summary>
        /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <value></value>
        /// <returns>
        /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        public int Count
        {
            get { return this.list.Count; }
        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
        /// </returns>
        public bool IsReadOnly
        {
            get { return false; }
        }

        /// <summary>
        /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </summary>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
        /// <returns>
        /// The index of <paramref name="item"/> if found in the list; otherwise, -1.
        /// </returns>
        public int IndexOf(IRoute item)
        {
            return this.list.IndexOf(item);
        }

        /// <summary>
        /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
        /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
        /// </exception>
        public void Insert(int index, IRoute item)
        {
            throw new NotImplementedException("Cannot insert a Route inside the Path");
        }

        /// <summary>
        /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the item to remove.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
        /// </exception>
        public void RemoveAt(int index)
        {
            this.Remove(this[index]);
        }

        /// <summary>
        /// Gets or sets the <see cref="IRoute"/> at the specified index.
        /// </summary>
        /// <value></value>
        public IRoute this[int index]
        {
            get { return this.list[index]; }
            set { throw new NotImplementedException("Cannot replace an item in Path"); }
        }

        #endregion
    }
}